/*
 * @Author: cyq
 * @Date: 2023-06-29 20:53:33
 * @Last Modified by: cyq
 * @Last Modified time: 2023-06-29 21:02:37
 */

import axios, { AxiosInstance, AxiosResponse } from "axios";
import { Notify } from "vant";

const request: AxiosInstance = axios.create({
  timeout: 5000,
});
// 添加请求拦截器
request.interceptors.request.use(
  function (config: any) {
    // 在发送请求之前做些什么
    const Authorization = localStorage.getItem("token");
    config.headers["Content-type"] = "application/json";
    config.headers["Authorization"] = `${Authorization}`;
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
request.interceptors.response.use(
  function (response: AxiosResponse) {
    // 对响应数据做点什么
    return response;
  },
  function (error: any) {
    // 对响应错误做点什么
    let status = error.response.status;
    switch (status) {
      case 401:
        Notify.error(error.response?.data.msg, 1, () => {
          const pathUrl = location.href.split("/");
          window.location.href = `/login?redirect=${encodeURIComponent(
            "/" + pathUrl[3]
          )}`;
        });
        break;
      case 404:
        console.log("页面找不到");
        break;
      case 500:
        console.log("后端错误");
        break;
    }
    return Promise.reject(error);
  }
);
export { request, axios };
